﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta name="Keywords" content="wizMobile" />
    <meta name="Description" content="wizMobile" />
    <meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <meta name="MobileOptimized" content="320" />
    <meta http-equiv="cleartype" content="on" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta name="apple-mobile-web-app-capable" content="yes"/>
    <meta name="apple-mobile-web-app-status-bar-style" content="white"/>
    <script type="text/javascript" src="../js/jquery.js"></script>
    <script LANGUAGE="JavaScript" TYPE="text/javascript" src="../js/urlparam.js"></script>
    <script LANGUAGE="JavaScript" TYPE="text/javascript" src="../js/wb_scormAdapter40.js"></script>
    <script LANGUAGE="JavaScript" TYPE="text/javascript" src="../js/mobile_common.js"></script>
    <style type="text/css">
        html{font-size:12px;width:100%;height:100%}
        body{width:100%;padding:0;margin:0;font-family:Microsoft Yahei,Arial; color:#333; min-width:320px;}
        #loading_text{ }
        .header .header-title{ line-height: 47px;display:block; font-size:18px; text-align:center; padding:0 50px 0 50px; text-overflow:ellipsis; overflow:hidden; white-space:nowrap;}

        /*头部返回*/
        .icon-back {
            width: 36px;
            height: 47px;
            position: absolute;
            left: 0;
        }
        .icon-back:before {
            content: "";
            float: left;
            width: 20px;
            height: 20px;
            /* background: url(../static/images/icon-03.png) no-repeat 0 -5px; */
            background-size: 20px;
            margin: 15px 0 0 13px;
        }
        .horizontal-screen {
            width: 46px;
            height: 100%;
            position: absolute;
            top: 0;
            right: 0;
        }
        .horizontal-screen > .title{
            width: 20px;
            margin: 0 auto;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100%;
        }
        .iphoneHeader{
            padding-top: 25px;
        }
    </style>
    <title>Cyberwisdom wizBank</title>
    <script type="text/javascript">
        var checkLoadInt=9527;
        var checkSendInt=9527;
        var my_aicc_url=getUrlParam('aicc_url');
        var my_aicc_sid=getUrlParam('aicc_sid');
        var my_web_launch=getUrlParam('web_launch');
        var my_cos_url=getUrlParam('cos_url');
        var tkhId = getUrlParam('tkh_id');
        var modId = getUrlParam('mod_id');
        var token = getUrlParam('token');
        var play_style = getUrlParam('play_style');
        var appUrl = getUrlParam('appUrl');

        var hasSendInt=9572;
        var IamHere=true;

        var had_sub=false;
        var counti=0;

        var lmsInitCalled ;
        var lmsFinishCalled ;

        var height;
        var width;

        var emb;


        // 获取url参数
        function getQueryVariable(variable) {
            var query = window.location.href.substring(1);
            var vars = query.split("&");
            for (var i=0;i<vars.length;i++) {
                var pair = vars[i].split("=");
                if(pair[0] == variable){return pair[1];}
            }
            return(false);
        }

        $(window).resize(function() {
            var newHeight = window.document.body.clientHeight;
            newHeight = newHeight-42;
            $("#scorm").height(newHeight);
        });

        function initTitle(isHorizontal){
            var lang = getQueryVariable('lang');
            var title = "";
            if(!isHorizontal) {
                if('en' == lang){
                    title = "Click here to save and exit";
                }else if('hk' == lang){
                    title = "點這裏退出並保存學習記錄";
                }else{
                    title = "点这里退出并保存学习记录";
                }
            } else {
                if('en' == lang){
                    title = "Save<br>and<br>exit";
                }else if('hk' == lang){
                    title = "储<br>存<br>并<br>退<br>出";
                }else{
                    title = "儲<br>存<br>並<br>退<br>出";
                }
            }
            $("#title").html(title);
        }
        var attempt = 0;
        $(function(){
            window.onload = function () {
            if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
                $('#header').addClass('iphoneHeader')
            }
              init() ;
              var oldWid = 0;
              var reg = new RegExp("^http(s)?:\/\/(.*?)\/");
              var url = my_aicc_url.match(reg);
              var mainUrl = url != null ? my_aicc_url.match(reg)[0] : '/';
              /*setInterval(function () {
                  $.ajax({
                      url:  mainUrl + 'app/track/module/time',
                      type: 'POST',
                      data: {'token': token, 'tkhId': tkhId, 'modId': modId, attempt : attempt++ == 0 ? 1 : 0},
                      async: true,
                      dataType: "json"
                  });
              }, 5000);*/

              //横竖屏切换
              var screenChange = function(docWidth, docheight) {
                if (!oldWid || oldWid !== docWidth) {
                  if(docWidth > docheight) {
                      this.initTitle(true);
                      $('#header').removeClass('header');
                      if(!$('#header').hasClass('horizontal-screen')) {
                          $('#header').addClass('horizontal-screen');
                      }
                      if(!$('#header').hasClass('title')) {
                          $('#header #title').addClass('title');
                      }
                      $('#sco_content').css('padding', '0');
                      $('#content').width(docWidth - 46);
                      $('#content').height(docheight);
                  } else {
                      this.initTitle(false);
                      if(!$('#header').hasClass('header')) {
                          $('#header').addClass('header');
                      }
                      $('#header').removeClass('horizontal-screen');
                      $('#header #title').removeClass('title');
                      /*$('#sco_content').css('padding-top', '46');*/
                      $('#content').width(docWidth);
                      $('#content').height(docheight - 46);
                  }
                  oldWid = docWidth
                }
              };

              var docWidth = document.body.clientWidth;
              var docheight = document.body.clientHeight;
              screenChange(docWidth, docheight);
              function windowResizeEvent(callback) {
                  var firstFire = null;
                  window.onresize = function () {
                      if(firstFire === null) {
                          firstFire = setTimeout(function() {
                              firstFire = null;
                              callback();
                          }, 100);
                      }
                  }
              }
              windowResizeEvent(function () {
                //获取网页可见区域宽度
                var docWidth = document.body.clientWidth;
                var docheight = document.body.clientHeight;
                screenChange(docWidth, docheight);
              })
            }
        });

        var initHistoryLength = 0;//此处设置全局初始化访问时，【历史页数】默认为0

        function init() {
            initHistoryLength = history.length;
            if (my_aicc_url != "" && typeof (my_aicc_url) != "undefined" && my_aicc_sid != "" && typeof (my_aicc_sid) != "undefined") {

                if(my_aicc_sid != undefined){
                    var temp = '';
                    var arr = my_aicc_sid.split(":_:_:");
                    if(arr.length > 4){
                        for(i=0;i<arr.length;i++) {
                            value = arr[i];

                            if(i==4){
                                today = new Date
                                value = _getTime(today)
                            }
                            temp = temp + value;
                            if(i < arr.length -1){
                                temp = temp + ':_:_:';
                            }
                        }
                        //alert('my_aicc_sid:'+my_aicc_sid +' temp='+temp)
                        my_aicc_sid = temp
                    }
                }
                let url = my_aicc_url
                if (appUrl){
                    url = appUrl + my_aicc_url
                }
                $.ajax({
                    type : 'POST',
                    dataType : 'text',
                    url : url,
                    headers: {
                        'token': token,
                        developer: 'mobile'

                    },
                    data : {
                        command : 'getparam',
                        version : '2.2',
                        sessionId : my_aicc_sid,
                        AICC_Data : '',
                        AU_password : ''
                    }
                }).done(function(data){
                    parseVar(data);
                });
            }
            window.addEventListener('orientationchange', function(event){
                dyniframesize('content');
            });
        }
        function parseVar(varStr) {
            if (varStr.substring(0, 7) == "error=0") {
                initSCORM_Var(varStr);

                var serverHost = window.location.protocol + "//" + window.location.host;
                var screenOrientation;
                if("many" === play_style){//横屏
                    screenOrientation = "landscape-primary";
                }else{//竖屏
                    screenOrientation = "portrait-primary";
                }

                openCourse(my_cos_url);
                lmsInitCalled = true;

                if(window.plus){

                    plus.screen.lockOrientation(screenOrientation);
                    changeBackButtion(function(){
                        scoPlayerSubmit();
                    });

                } else {
                    document.addEventListener('plusready',function(){
                        plus.screen.lockOrientation(screenOrientation);

                        changeBackButtion(function(){
                            scoPlayerSubmit();
                        });

                    },false);
                }
            }
        }

        var time_spend=0;
        var prevTime=0;
        var cosPutTime = 10;        //每90s重置下推送开关允许推送
        var putFlag = false;
        function timeCount() {
            time_spend = time_spend + 1;
            if(time_spend % cosPutTime == 0) {
                putFlag = true;
            }
        }

        function _getTime(datetime){

            if ( datetime.getMonth() > 9 )
                month = datetime.getMonth() + 1
            else
                month = '0' + (datetime.getMonth() + 1 )

            if ( datetime.getDate() > 9 )
                day = datetime.getDate()
            else
                day = '0' + datetime.getDate()

            if ( datetime.getHours() > 9 )
                hour = datetime.getHours()
            else
                hour = '0' + (datetime.getHours() + 1 )

            if ( datetime.getMinutes() > 9 )
                minutes = datetime.getMinutes()
            else
                minutes = '0' + datetime.getMinutes()

            if ( datetime.getSeconds() > 9 )
                seconds = datetime.getSeconds()
            else
                seconds = '0' + datetime.getSeconds()

            time = datetime.getFullYear() + month + day + hour  + minutes  + seconds

            return time;

        }

        function openCourse(course_url){
            $("#content").remove();
            var htm = '<iframe id="content" src="'+ course_url+'"  style="display: none;" name="content" width="100%" scrolling="no" frameborder="0" />'
            $("#sco_content").html(htm)
            dyniframesize('content')
            window.setInterval("timeCount()", 1000);
        }
        function joinAiccData(){
            var aiccDataVar="";
            var NEWL = "\r\n";
            aiccDataVar+="[core]" + NEWL;
            aiccDataVar+="lesson_location=" +wiz_cmi_core_lesson_location+ NEWL;
            aiccDataVar+="lesson_status=" +wiz_cmi_core_lesson_status+ NEWL;
            aiccDataVar+="score=" +wiz_cmi_core_score_raw+","+wiz_cmi_core_score_max+","+wiz_cmi_core_score_min+ NEWL;

            aiccDataVar+="time=" +time_spend+ NEWL;

            aiccDataVar+="[core_lesson]" + NEWL;
            aiccDataVar+=encodeURIComponent(wiz_cmi_suspend_data)+ NEWL;
            return aiccDataVar;
        }

        function putToSendAdapter(){
            if (!putFlag) {
                return;
            }
            putFlag = false;
          // 当前时间-上一次提交得时间
          scoPlayerSubmit(true)
            // if (my_aicc_url != "" && typeof (my_aicc_url) != "undefined") {
            //     $.ajax({
            //         type : 'POST',
            //         dataType : 'text',
            //         url : my_aicc_url,
            //         data : data
            //     }).done(function(data){
            //     });
            // }
        }

        function scoPlayerSubmit(before = false){
            console.log(my_aicc_sid, 'my_aicc_sid')

            if("VIEWONLY" == my_aicc_sid){//预览的时候，直接返回
                goBack();
                return;
            }
            console.log(had_sub, 'had_sub')
            if(had_sub){
                return;
            }
            if(lmsInitCalled){
                var url = my_aicc_url ;
                if (appUrl){
                    url = appUrl + my_aicc_url
                }
                if(wiz_cmi_core_score_raw=='NaN'){
                    wiz_cmi_core_score_raw=0;
                }
                

                //课件的学习时长，由打开课件时间开始算，不再依赖课件传回来的时间
                //time_ = wiz_cmi_core_session_time
                //aiccDataVar+="time=" +wiz_cmi_core_session_time+ NEWL;
                var putPrevTime = time_spend
                // 当前时间-上一次提交得时间
                var updateTime = putPrevTime - prevTime
                var data = {
                    command: 'putparam',
                    version: '2.2',
                    type: 'scorm',
                    sessionId:my_aicc_sid,
                    auPassword: '',
                    //core
                    lessonLocation : wiz_cmi_core_lesson_location,
                    lessonStatus:wiz_cmi_core_lesson_status,
                    score: wiz_cmi_core_score_raw,
                    maxScore: wiz_cmi_core_score_max,
                    minScore: wiz_cmi_core_score_min,
                    time: updateTime,
                    coreLesson : encodeURIComponent(wiz_cmi_suspend_data)
                }

                if (updateTime && wiz_cmi_core_lesson_status === 'not attempted'){
                    data.lessonStatus = 'failed'
                }

                $.ajax({
                    url: url,
                    headers: {
                        'token': token,
                        developer: 'mobile',

                    },
                    data : data,
                    async : false,
                    method : 'POST',
                    contentType : 'application/x-www-form-urlencoded',
                    success: function (resp) {
                        prevTime = putPrevTime;
                        if (before) {
                            return true;
                        } else {
                            goBack();
                            unlockOrientation();
                            return resp;
                        }
                    },
                    error: function (errResp) {
                        return errResp;
                    }
                })
            }else{
                goBack();
                unlockOrientation();
            }
        }

        var goBack = function(){

            var goBackHistoryLength = history.length;//设置访问页数变量
            var goLenth = goBackHistoryLength - initHistoryLength;//开始计算返回的页数：当前历史页 - 初始化时的页数
            initHistoryLength = 0;//初始化的数值使用完之后，首先将它重置回0;

            if(window.plus){
                if(plus.webview.currentWebview().opener()){
                    changeWebviewDetail(plus.webview.currentWebview().opener().id,function(){
                        var ws = plus.webview.currentWebview();
                        ws.close('auto',200);
                    });
                }else{
                    var ws = plus.webview.currentWebview();
                    ws.close('auto',200);
                }
            } else if(goBackHistoryLength>1){
                goLenth = parseInt(goLenth)+1;//因为需要返回到上一层页，所以要加一，正如 history.go(-1)
                var realGoLenth = - goLenth; //赋为负数使用
                realGoLenth = parseInt(realGoLenth);//转为数值类型
                history.go(realGoLenth);//按照计算结果进行层级返回
            } else{
                w.close();
            }
        };
        window.onresize=function(){
            dyniframesize('content');
        }
        function dyniframesize(id) {
            //debugger;
            var ifm= document.getElementById(id);
            if(!ifm){
                return;
            }

            var subWeb = document.frames ? document.frames[id].document : ifm.contentDocument;
            if(ifm != null && subWeb != null) {
                ifm.height = window.document.body.clientHeight;
                ifm.width = window.document.body.clientWidth;
                //横屏和竖屏
                if(ifm.height > ifm.width) {
                    ifm.height = ifm.height - 46;
                } else {
                    ifm.width = ifm.width - 46;
                }
            }
            //由于每次调用$("#sco_content").html(htm)， 这个对象都会被清空。所以不用再去删除。
            // 所以只是在onresize的时候改对象是存在的，并且被置为隐藏。所以不会再多次出现，也不会创建
            if($("#loading_text") && $("#loading_text").length < 1) {
                var lang = getUrlParam("lang");
                if(lang == ""){
                    lang = 'en'
                }
                var wb_msg_loading_msg = "Loading... Please wait."
                if(lang =='ch'){
                    wb_msg_loading_msg = "下載中，請稍候...";
                }else if(lang =='gb'){
                    wb_msg_loading_msg = "装载中，请稍候...";
                }
                $("#sco_content").append('<div id="loading_text">' + wb_msg_loading_msg + '</div>');
            }
            $('iframe#' + id).load(function(){
                var ifm = document.getElementById(id);
                if(!ifm){
                    return;
                }
                var subWeb = document.frames ? document.frames[id].document : ifm.contentDocument;
                if(ifm != null && subWeb != null) {
                    ifm.width = window.document.body.clientWidth;
                    ifm.height = window.document.body.clientHeight;
                    //横屏和竖屏
                    if(ifm.height > ifm.width) {
                        ifm.height = ifm.height - 46;
                    } else {
                        ifm.width = ifm.width - 46;
                    }
                }
                $("#loading_text").hide();
                $("#" + id).show();
            })
        }

        /*
        * 递归获取页面的所有的iframe（包括iframe中还有iframe，即iframe嵌套）
        */
        function getChildIframes(pIframe,allIframes){

            if(pIframe){
                var childIframes = pIframe.frames;
                if(childIframes && childIframes.length>0){

                    for(var i=0;i<childIframes.length;i++){
                        var cIframe = childIframes[i];
                        allIframes.push(cIframe);
                        getChildIframes(cIframe,allIframes);
                    }

                }
            }

        }

        /*
        *获取页面的所有的iframe
        */
        function getAllIframes(){

            var allIframes = [];

            getChildIframes(window,allIframes);

            return allIframes;
        }

        //app原生事件监听，app界面隐藏时触发
        document.addEventListener('pause', function(){

            //递归获取页面的所有的iframe（包括iframe中还有iframe，即iframe嵌套）
            var allIframes = getAllIframes();

            /*
            * 循环页面所有iframe中的所有video（双重循环），依次停止video
            */
            if(allIframes && allIframes.length>0){
                for(var i=0;i<allIframes.length;i++){
                    var iframe = allIframes[i];
                    var iframeVideos = iframe.document.getElementsByTagName("video");
                    if(iframeVideos && iframeVideos.length>0){
                        for(var j=0;j<iframeVideos.length;j++){
                            var video = iframeVideos[j];
                            video.pause();
                        }
                    }
                }
            }

        });
        // 接收父级页面传过来的信息
        window.addEventListener('message', function(e){
            if(e.data == 'scoPlayerSubmit'){
                scoPlayerSubmit('true');
            }
        })
    </script>
</head>

<body style="height:100%;background:#f4f4f4;" >

<div id="sco_content">
    <iframe id="content"  style="display: none;" src="./loading.htm" name="content" onload="javascript:dyniframesize('content');" width="100%"
            scrolling="yes" frameborder="0" />
</div>
</body>
</html>
